<?php

namespace common\service;

use common\exception\LogicException;
use common\model\MediaServerModel;
use Exception;
use support\ErrorCode;
use support\SingletonTrait;

class MediaService
{
    // 单例工具
    use SingletonTrait;


    /**
     * 生成处理媒体添加数据
     * @param $data
     * @param array $mediaServerParam
     * @return mixed
     * @throws Exception
     */
    public function generateMediaData(&$data, array $mediaServerParam = [])
    {
        $mediaData = $data;

        if (!empty($mediaServerParam)) {
            $mediaServerData = $mediaServerParam;
        } elseif (!empty($data['request_url'])) {
            // 利用media_data里的request_url来重置媒体服务器的request_url
            $mediaServerData['request_url'] = $data['request_url'];
        } else {
            if (empty($data['media_server_id'])) {
                // media_server_id 抛出异常
                throw new LogicException('media_server_id does not exist.', ErrorCode::MEDIA_SERVER_NOT_EXIST);
            } else {
                // 获取当前media server数据
                $mediaServer = MediaService::getInstance();
                $mediaServerData = $mediaServer->getMediaServerData($data['media_server_id']);

                if (!$mediaServerData) {
                    // 无效的媒体服务器
                    throw new LogicException('Invalid media server.', ErrorCode::MEDIA_SERVER_INVALID);
                }
            }
        }

        $mediaSize = '';
        $thumbUrl = '';
        switch ($data["type"]) {
            case 'video':
                // 视频保存原始尺寸
                $mediaSize = "{$data["width"]}x{$data["height"]}";
                $pathTrim = str_replace('/' . $data['md5_name'] . '/', '', $data['path']);
                $thumbUrl = $mediaServerData['request_url'] . '/' . $pathTrim . $data['thumb'];
                break;
            case 'image':
                // 获取图片上传尺寸
                $mediaSize = $data["size"];
                $sizeArray = explode(',', $data["size"]);
                $minSize = 999999;
                $minSizeString = 'origin';
                foreach ($sizeArray as $sizeItem) {
                    if ($sizeItem !== 'origin' && strpos($sizeItem, 'x') !== false) {
                        if (explode('x', $sizeItem)[0] < $minSize) {
                            $minSizeString = $sizeItem;
                        }
                    }
                }
                $thumbUrl = "{$mediaServerData['request_url']}/{$data['path']}{$data['md5_name']}_{$minSizeString}.{$data['ext']}";
                break;
        }

        if (!array_key_exists("base_url", $mediaData)) {
            // 缩略图地址
            $mediaData["base_url"] = $mediaServerData['request_url'] . "/" . $mediaData['path'];
        }

        // 缩略图尺寸
        $data["size"] = $mediaSize;

        // 缩略图相对路径
        $data["thumb"] = $thumbUrl;

        // 缩略图参数
        $data["param"] = $mediaData;

        return $data;
    }

    /**
     * 获取指定媒体服务器数据
     * @param $mediaServerId
     * @return array|mixed
     * @throws Exception
     */
    public function getMediaServerData($mediaServerId)
    {
        $mediaServiceModel = model(MediaServerModel::class);
        return $mediaServiceModel->findData([
            "fields" => 'id,name,upload_url,request_url,access_key,secret_key',
            "filter" => [
                'id' => $mediaServerId
            ]
        ]);
    }

}
